<?php
include_once '../icloud_files/system/DB.php';


class ServiceCentersModel extends DB {

    public $messages, $center_data;
/* ------------------------------------------------------------------------------------------------- */


    public function add_auto_service_center($data, $pic) {
        //input norm, valid, checks
        foreach ($data as $k => $v) {
            $this->center_data[$k] = $this->db_connection->real_escape_string(trim($v));
        }

        //add center to database
        $result = $this->db_connection->query("INSERT INTO auto_service_centers
            (business_type, company_name, contact_person, phone, email, city, postal_code, state) VALUES (
            '".$this->center_data['business_type']."',
            '".$this->center_data['company_name']."',
            '".$this->center_data['contact_person']."',
            '".$this->center_data['phone']."',
            '".$this->center_data['email']."',
            '".$this->center_data['city']."',
            '".$this->center_data['postal_code']."',
            '".$this->center_data['state']."')");

        if($result) {
            //upload company logo to server and add link to database
            if($pic['company_logo']['error'] === UPLOAD_ERR_OK) {
                $center_id = $this->db_connection->insert_id;
                $tmp_path = $pic['company_logo']['tmp_name'];
                $dir =  'img/user_data/auto_service_center_logos/';
                if(!is_dir($dir)) {
                    mkdir($dir, 0777, true);
                }
                $new_path = $dir.'center_id_'.$center_id.'.'.pathinfo($pic['company_logo']['name'], PATHINFO_EXTENSION);

                if(!move_uploaded_file($tmp_path, $new_path)) {
                    $this->messages[] = 'The company logo could not be uploaded. Please try again later.';
                } else {
                    $this->db_connection->query("UPDATE auto_service_centers SET logo='$new_path'
                        WHERE center_id={$center_id}");

                    if($this->db_connection->affected_rows !== 1) {
                        $this->messages[] = 'The company logo could not be uploaded. Please try again later.';
                    }
                }
            }

            $this->messages[] = 'The Auto Service Center '.$this->center_data['company_name'].
                ' has been added successfully to the database.';
        } else {
            $this->messages[] = 'There has been a problem with your request. We are sorry for the inconvenience, please try again later.';
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */

}